package com.imooc.ecommerce.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.imooc.ecommerce.fallback_handler.CustomFallbackHandler;
import com.imooc.ecommerce.vo.JwtToken;
import com.imooc.ecommerce.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * Sentinel提供容错降级的功能
 *
 * @author zhangshao
 * @since 2023/12/6 23:34
 */
@Slf4j
@RestController
@RequestMapping("/sentinel-fallback")
@SuppressWarnings("all")
public class SentinelFallbackController {

    /**
     * 注入没有增强的RestTemplate
     */
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/get-token")
    @SentinelResource(value = "getTokenFromAuthorityService", fallback = "getTokenFromAuthorityServiceFallback", fallbackClass = CustomFallbackHandler.class)
    public JwtToken getTokenFromAuthorityService(@RequestBody UsernameAndPassword usernameAndPassword) {
        String requestUrl = "http://127.0.0.1:7000/ecommerce-authority-center/authority/token";
        log.info("RestTemplate request url and body:[{}],[{}]", requestUrl, JSON.toJSONString(usernameAndPassword));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return restTemplate.postForObject(requestUrl, new HttpEntity<>(JSON.toJSONString(usernameAndPassword), headers), JwtToken.class);
    }

    /**
     * 让Sentinel忽略一些异常
     *
     * @param code
     * @return
     */
    @GetMapping("/ignore-exception")
    @SentinelResource(value = "ignoreException", fallback = "ignoreExceptionFallback", fallbackClass = {CustomFallbackHandler.class}, exceptionsToIgnore = {NullPointerException.class})
    public JwtToken ignoreException(Integer code) {
        if (code % 2 == 0) {
            throw new NullPointerException("you input code is:" + code);
        }
        return new JwtToken("qiyi-imooc");
    }


}
